package com.ben.multiple.schedule;

import java.time.LocalDateTime;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ben
 * @date 2019/7/7
 */
@RestController
@RequestMapping("/cron")
@Slf4j
@ConfigurationProperties(prefix = "multiple")
public class CronResource {
    /**
     * 默认周期
     * 从 0秒 开始，每隔 15秒，执行一次
     */
    private static String cron = "0/15 * * * * *";

    /**
     * 占位符取值，从配置文件取值，设置默认值
     */
    @Scheduled(cron = "${multiple.cron:'*/20 * * * * *'}")
    public void simple() {
        System.out.println("simple:" + LocalDateTime.now() + "==" + Thread.currentThread().getName());
    }

    @Bean
    public SchedulingConfigurer scheduleDynamic() {
        return taskRegistrar -> taskRegistrar.addTriggerTask(
                // 定时任务的具体业务
                () -> System.out.println("Dynamic:" + LocalDateTime.now() + "==" + Thread.currentThread().getName()),
                // 动态更新周期
                triggerContext -> new CronTrigger(CronResource.cron).nextExecutionTime(triggerContext).toInstant());
    }

    @PutMapping
    public Boolean update(@RequestBody Map<String, String> body) {
        String cron = body.get("cron");
        log.info("旧：{}, 新：{}", CronResource.cron, cron);
        CronResource.cron = cron;
        return true;
    }
}
